﻿using JsonConversion;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web.Mvc;
using RTracker.Models.Common;
using RTracker.Models.ErrorLog;
using System.Web.Security;

namespace RTracker.Areas.Recruitment.Models.Shift
{
    public class MShift
    {
        /// static variable RowSize from config settings to get list of this row size.
        public static int nRowSize = Convert.ToInt32(ConfigurationManager.AppSettings["TotalRecordsInListShift"]);

        /// <summary>
        /// This method is used to create a shift in the database.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCShift">This object contains details of the Shift.</param>
        /// <returns>CStatus which is an object that contain transaction details</returns>
        public CStatus CreateShift(CAuthenticationContext objCAuthenticationContext, ref CShift objCShift)
        {
            CStatus oCStatus = new CStatus();

            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("r_create_shift_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@organization_id", SqlDbType.BigInt).Value = objCShift.OrganizationId;
                    cmd.Parameters.Add("@shift_desc", SqlDbType.NVarChar).Value = objCShift.ShiftDesc;
                    cmd.Parameters.Add("@shift_name", SqlDbType.Int).Value = objCShift.ShiftName;
                    cmd.Parameters.Add("@shift_start_time", SqlDbType.Int).Value = objCShift.ShiftStartTime;
                    cmd.Parameters.Add("@shift_end_time", SqlDbType.Int).Value = objCShift.ShiftEndTime;

                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                    cmd.ExecuteNonQuery();

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                    }
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }
            return oCStatus;
        }

        /// <summary>
        /// This method is used to delete a shift in the database.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCShift">This object contains details of the shift.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus DeleteShift(CAuthenticationContext objCAuthenticationContext, ref CShift objCShift)
        {
            CStatus oCStatus = new CStatus();

            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("r_delete_shift_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@created_by", SqlDbType.Int).Value = objCAuthenticationContext.UserId;
                    cmd.Parameters.Add("@shift_ids", SqlDbType.NVarChar).Value = objCShift.ShiftIds;

                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                    cmd.ExecuteNonQuery();

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                    }
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }
            return oCStatus;
        }

        /// <summary>
        /// This method is used to update the shift detail in the database.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCShift">This object contains details of the shift.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus UpdateShift(CAuthenticationContext objCAuthenticationContext, ref CShift objCShift)
        {
            CStatus oCStatus = new CStatus();

            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("r_update_shift_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;

                    cmd.Parameters.Add("@organization_id", SqlDbType.BigInt).Value = objCShift.OrganizationId;
                    cmd.Parameters.Add("@shift_id", SqlDbType.BigInt).Value = objCShift.ShiftId;
                    cmd.Parameters.Add("@shift_desc", SqlDbType.NVarChar).Value = objCShift.ShiftDesc;
                    cmd.Parameters.Add("@shift_name", SqlDbType.Int).Value = objCShift.ShiftName;
                    cmd.Parameters.Add("@shift_start_time", SqlDbType.Int).Value = objCShift.ShiftStartTime;
                    cmd.Parameters.Add("@shift_end_time", SqlDbType.Int).Value = objCShift.ShiftEndTime;

                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                    cmd.ExecuteNonQuery();

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                    }
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }
            return oCStatus;
        }

        /// <summary>
        /// This method is used to get the shift detail in the database.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCShift">This object contains details of the shift.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus GetShiftDetail(CAuthenticationContext objCAuthenticationContext, ref CShift objCShift)
        {
            CStatus oCStatus = new CStatus();
            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    SqlCommand cmd = new SqlCommand("r_get_shift_detail_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;

                    cmd.Parameters.Add("@shift_id", SqlDbType.Int).Value = objCShift.ShiftId;
                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;

                    SqlDataAdapter adp = new SqlDataAdapter(cmd);

                    DataTable dt = new DataTable();

                    int rowsAffected = adp.Fill(dt);

                    if (rowsAffected > 0)
                    {
                        objCShift = dt.ConvertToListFromDataTableShift()[0];
                    }

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.DetailSuccess;
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                    }
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }
            return oCStatus;
        }

        /// <summary>
        /// Sets the softlock on the record whose Id is passed.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCShift">This object contains details of the shift.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus SetShiftSoftLock(CAuthenticationContext objCAuthenticationContext, CShift objCShift)
        {
            CStatus oCStatus = new CStatus();

            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("r_set_shift_soft_lock_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@shift_id", SqlDbType.Int).Value = objCShift.ShiftId;
                    cmd.Parameters.Add("@created_by", SqlDbType.Int).Value = objCAuthenticationContext.UserId;

                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                    cmd.ExecuteNonQuery();

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                    }
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }
            return oCStatus;
        }

        /// <summary>
        /// Sets the hardlock on the record whose Id is passed.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCShift">This object contains details of the shift.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus SetShiftHardLock(CAuthenticationContext objCAuthenticationContext, CShift objCShift)
        {
            CStatus oCStatus = new CStatus();

            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("r_set_shift_hard_lock_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@shift_id", SqlDbType.Int).Value = objCShift.ShiftId;
                    cmd.Parameters.Add("@created_by", SqlDbType.Int).Value = objCAuthenticationContext.UserId;

                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                    cmd.ExecuteNonQuery();

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                    }
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }
            return oCStatus;
        }

        /// <summary>
        /// Releases the softlock on the record whose Id is passed.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCShift">This object contains details of the shift.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus ReleaseShiftSoftLock(CAuthenticationContext objCAuthenticationContext, CShift objCShift)
        {
            CStatus oCStatus = new CStatus();

            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("r_release_shift_soft_lock_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@shift_id", SqlDbType.Int).Value = objCShift.ShiftId;
                    cmd.Parameters.Add("@created_by", SqlDbType.Int).Value = objCAuthenticationContext.UserId;

                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                    cmd.ExecuteNonQuery();

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                    }
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }
            return oCStatus;
        }

        /// <summary>
        /// Releases the hardlock on the record whose Id is passed.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCShift">This object contains details of the shift.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus ReleaseShiftHardLock(CAuthenticationContext objCAuthenticationContext, CShift objCShift)
        {
            CStatus oCStatus = new CStatus();

            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("r_release_shift_hard_lock_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@shift_id", SqlDbType.Int).Value = objCShift.ShiftId;
                    cmd.Parameters.Add("@created_by", SqlDbType.Int).Value = objCAuthenticationContext.UserId;

                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                    cmd.ExecuteNonQuery();

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                    }
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }
            return oCStatus;
        }

        /// <summary>
        ///  This function is used to get complete Shift list
        /// </summary>
        /// <returns>List of type CShift</returns>
        public GShift GetShiftGridList(CShift objCShift, CAuthenticationContext objCAuthenticationContext)
        {
            GShift objGShift = new GShift();
            int nTotalRecords = 0;
            int nCurrentRowSize = nRowSize;

            if (objCShift.RowSize != 0)
            {
                nCurrentRowSize = objCShift.RowSize;
            }
            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    SqlCommand cmd = new SqlCommand("r_get_shift_paging_list_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@shift_id", SqlDbType.Int).Value = objCShift.ShiftId;
                    cmd.Parameters.Add("@organization_id", SqlDbType.Int).Value = objCShift.OrganizationId;
                    cmd.Parameters.Add("@page_number", SqlDbType.Int).Value = objCShift.PageNumber;
                    cmd.Parameters.Add("@row_size", SqlDbType.Int).Value = nCurrentRowSize;
                    cmd.Parameters.Add("@sort_on", SqlDbType.VarChar).Value = objCShift.SortOn;
                    cmd.Parameters.Add("@sort_type", SqlDbType.VarChar).Value = objCShift.SortType;
                    cmd.Parameters.Add("@search", SqlDbType.VarChar).Value = objCShift.Search;
                    cmd.Parameters.Add("@searchon", SqlDbType.VarChar).Value = objCShift.SearchOn;
                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    cmd.Parameters["@error"].Direction = ParameterDirection.Output;
                    SqlDataAdapter adp = new SqlDataAdapter(cmd);

                    DataTable dt = new DataTable();

                    int rowsAffected = adp.Fill(dt);

                    objGShift.Paging = new CPaging();
                    if (rowsAffected > 0)
                    {

                        objGShift.LstShift = dt.ConvertToListFromDataTableShift();
                        objGShift.LstShift[0].PageNumber = int.Parse(cmd.Parameters["@idOut"].Value.ToString());
                        objGShift.Paging.PageNumber = objGShift.LstShift[0].PageNumber;
                    }
                    else
                    {
                        objGShift.LstShift = null;
                    }


                    nTotalRecords = int.Parse(cmd.Parameters["@error"].Value.ToString());

                    objGShift.Status = new CStatus();

                    if (nTotalRecords < 0)
                    {
                        objGShift.Status.Success = false;
                        objGShift.Status.StatusDetails = nTotalRecords.DbError();
                    }
                    else
                    {
                        objGShift.Paging.TotalRecordsCount = nTotalRecords;
                        objGShift.Paging.PageSize = nCurrentRowSize;

                        objGShift.Status.Success = true;
                        objGShift.Status.StatusDetails = "success";
                    }
                }
                catch (Exception ex)
                {
                    objGShift.Status = new CStatus();
                    objGShift.Status.Success = false;
                    objGShift.Status.StatusDetails = ex.Message;
                }
            }
            return objGShift;
        }

        /// /// <summary>
        ///  This function is used to get complete Shift list working under a same organization.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about Shift's authentication context.</param>
        /// <param name="objCShift">This object contains details of the Shift.</param>
        /// <param name="lstCShift">"out" the list of Shifts</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus GetShiftList(CAuthenticationContext objCAuthenticationContext, int organizationId, out List<CShift> lstCShift)
        {
            CStatus oCStatus = new CStatus();
            lstCShift = new List<CShift>();
            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("r_get_shift_list_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@organization_id", SqlDbType.Int).Value = organizationId;

                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    SqlDataAdapter adp = new SqlDataAdapter(cmd);

                    DataTable dt = new DataTable();

                    int rowsAffected = adp.Fill(dt);

                    if (rowsAffected > 0)
                    {
                        lstCShift.AddRange(dt.ConvertToListFromDataTableShift());
                    }

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                        //oCStatus.StatusDetails = CAppErrorsConstants.SomethingWentWrong;
                    }
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }
            return oCStatus;
        }
    }
}